package com.nowcoder.community.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.exception.KaptchaNotMatchException;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CookieUtil;
import com.nowcoder.community.util.RedisKeyUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.ObjectUtils;

/**
 * @author szq
 * @create 2023-02-28 8:07
 * @description
 */
@Data
public class KaptchaFilter extends UsernamePasswordAuthenticationFilter {

    private static final String FORM_KAPTCHA_KEY = "kaptcha";

    private String kaptchaParameter = FORM_KAPTCHA_KEY;

    private RedisTemplate redisTemplate;

    private final UserService userService;

    public KaptchaFilter(RedisTemplate redisTemplate, UserService userService) {
        this.redisTemplate = redisTemplate;
        this.userService = userService;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        request.getSession().setAttribute("username", username);
        request.getSession().setAttribute("password", password);
        // 1.从请求中获取验证码
        String verifyCode = request.getParameter(getKaptchaParameter());
        // 2.与session中的验证码进行比较
        //String sessionVerifyCode = (String) request.getSession().getAttribute("kaptcha");
        String kaptcha = null;
        String kaptchaOwner = CookieUtil.getValue(request, "kaptchaOwner");
        if (StringUtils.isNotBlank(kaptchaOwner)){
            // 查询验证码
            String redisKey = RedisKeyUtil.getKaptcha(kaptchaOwner);
            kaptcha = redisTemplate.opsForValue().get(redisKey).toString();
        }

        if (!ObjectUtils.isEmpty(kaptcha) && !ObjectUtils.isEmpty(verifyCode)
                && kaptcha.equalsIgnoreCase(verifyCode)) {
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
            if (user != null && user.getStatus() == 0){
                throw new UsernameNotFoundException("账号未激活!");
            }
            return super.attemptAuthentication(request, response);
        }
        throw new KaptchaNotMatchException("验证码不匹配!");
    }
}
